package main

import (
	"fmt"
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Product struct {
	// gorm.Model
	// ID        uint
	CreatedAt time.Time `gorm:"primarykey"`
	SN        uint      `gorm:"primarykey"`

	Code  string
	Price uint
}

func main() {
	db, err := gorm.Open(sqlite.Open("test2.db"), &gorm.Config{
		SkipDefaultTransaction: true,
	})
	if err != nil {
		panic("failed to connect database")
	}

	// Migrate the schema
	db.AutoMigrate(&Product{})
	var sn uint
	for {
		// Create
		db.Create(&Product{Code: "D42", Price: 100, SN: sn})
		time.Sleep(time.Second)
		sn++
	}

	// Read
	var product Product
	db.First(&product, 1)                 // find product with integer primary key
	db.First(&product, "code = ?", "D42") // find product with code D42
	fmt.Println(product)

	// Update - update product's price to 200
	db.Model(&product).Update("Price", 200)
	// Update - update multiple fields
	db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
	db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

	// Delete - delete product
	// db.Delete(&product, 1)
	time.Sleep(10 * time.Minute)
}
